<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
class InfoCaiji extends \app\BaseController{
    public $modelid,$catid,$cat,$ModelInfo;
    public function __construct(\think\App $app) {
        parent::__construct($app);
        $this->error("已关闭采集发布模块");
        //采集的信息直接以admin账号发送
        $this->user_id=     1;
        $this->username=    "admin";
        $config_fabu_pass="";
        $get_fabu_pass=Request::param('fabu_pass');
        if(!$get_fabu_pass){
            $this->error("发布密码不能为空！");
        }
        if(!$get_fabu_pass||$get_fabu_pass!=$config_fabu_pass){
            $this->error("发布密码错误！");
        }        
    }
    
    public function add(){
       //获取catid
        $catid=Request::param('catid',0,"intval");
        $this->cat= $GLOBALS['cat'][$catid]; 
        View::assign("cat",$this->cat);        
        $this->catid=$catid;
        if(!$this->cat){
            $this->error("栏目信息不存在");
        }
        //
        $this->modelid=$this->cat["modelid"];
        $this->ModelInfo=$GLOBALS["model"][$this->modelid];
        //当前模型，用于调用里面的方法
        $this->model=new \app\admin\model\InfoModel();
        //路由模型
        $this->RouteModel=new \app\admin\model\RouteModel();
        //切换后缀 
        $this->model->setSuffix($this->cat["table_name"]);
        //
        $this->model->ModelInfo=$this->ModelInfo;//向模型里注入当前的模型表信息
        $this->model->cat=$this->cat;//向模型里注入当前的栏目信息
        //对应的模型的模型
        $this->ModelModel=new \app\admin\model\ModelModel();
        //数据库字段表
        $this->TableFieldModel=new \app\admin\model\TableFieldModel();
        $this->validate=new \app\admin\validate\InfoValidate();        
        
        $result=$this->save("add");
        echo "success";exit;
    }
   
    private function save($type){
        $data=$this->request->param();
        $pubid= make_pubid();
        $data['pubid']=$pubid;
        $_POST["pubid"]=$pubid;
        //检测titleurl是否合格
        if($data['titleurl']){
            if(!preg_match("/^\/[\w|\/]+\.html$/i", $data['titleurl'])){
                $this->error("自定义链接枨错误，只能使用[数字，字母，_，/],并以/开头.html结尾");
            }
        }
        //数据加工处理(返回的包括主表和副表的数据)
        $CreateData=$this->dataCreate($data,$type);
        //print_r($CreateData);exit;
        //先存到缓存表里
        if($data["action_type"]=="draft"){
            //放到缓存表并且将状态设置为【草稿】
            $cache_id=$this->model->saveCache($CreateData,"draft");
        }else{
            //提交审核
            $cache_id=$this->model->saveCache($CreateData,"readyCheck");
            //系统是否自动审核||针对已审核的信息，修改后还是直接审核
            if($this->ModelInfo["autochecked"]||$this->model->find($data["id"])){
                $id=$this->model->setCheckCache($cache_id);
            }
        }
        //更新路由
        $this->RouteModel->updateInfoRoute();//更新路由
        //
        return ["cache_id"=>$cache_id,"id"=>$id];
    } 
    private function dataCreate($data,$type="add"){//$type为添加来源，add:后台添加 update:后台修改 import_add:导入[增加] import_update:导入[修改]
        $return=[];
        //录入项
        $is_enter=$this->ModelInfo["is_enter"];
        $is_enter_arr=explode(",",trim($is_enter,","));
        //
        $where=[];
        $where[]=["table_id","=",$this->ModelInfo["table_id"]];
        $where[]=["field","in",$is_enter_arr];
        $fieldarr=$this->TableFieldModel->where($where)->select();
        foreach($fieldarr as $v){
            //如果是导入的，判断这个字段是否在导入的数据里存在，如果不存在不做下一步处理
            if(($type=="import_add"||$type=="import_update")&&!isset($data[$v['field']])){
                continue;
            }  
            //复选框 多选下拉
            if($v['formtype']=="checkbox"||$v['formtype']=="selects"){
                //为数据导入的时候，表格里填写的是:上网|听音乐|打游戏 只要两边增加|即可
                if($type=="import_add"||$type=="import_update"){
                    if($data[$v['field']]){
                        $data[$v['field']]="|".$data[$v['field']]."|";
                    }
                }else{
                    $data[$v['field']]=implode("|",$data[$v['field']]);
                    if($data[$v['field']]){
                        $data[$v['field']]="|".$data[$v['field']]."|";
                    }
                }                
            }
            //多图上传
            if($v['formtype']=="morepic"){
                $morepic_str="";
                $smallimg=$data[$v['field']."_smallimg"];
                $bigimg=$data[$v['field']."_bigimg"];
                $imgname=$data[$v['field']."_imgname"];
                foreach($smallimg as $key=>$val){
                    $morepic_str.=$smallimg[$key]."||".$bigimg[$key]."||".$imgname[$key]."\r\n";
                }
                $morepic_str=trim($morepic_str,"\r\n");
                $data[$v['field']]=$morepic_str;
            }  
            //多值字段
            if($v['formtype']=="morevalue"){
                $morevalue_str="";
                $fieldLen=$data[$v['field']."_morevalue_len"];//获取一共有多少列字段
                $fieldValArr=array();
                foreach($fieldLen as $k1=>$v1){
                    $fieldValArr[$k1]=$data[$v['field']."_".$k1];
                }
                //根据第一列字段，提取有多个行数据,并循环
                foreach($fieldValArr[0] as $k2=>$v2){
                    //单个信息
                    $row_str="";
                    foreach($fieldValArr as $k3=>$fieldVal){
                        if($k3>0){
                            $row_str.="{{FieldSplit}}".$fieldVal[$k2];
                        }else{
                            $row_str=$fieldVal[$k2];
                        }
                    }
                    //多行信息拼接
                    if($morevalue_str){
                        $morevalue_str.="{{RsSplit}}".$row_str;
                    }else{
                        $morevalue_str=$row_str;
                    }
                }
                $data[$v['field']]=$morevalue_str;
            }             
            //日期
            if($v['formtype']=="date"){
               $data[$v['field']]=$data[$v['field']]?strtotime($data[$v['field']]):"";
            }    
            //如果是编辑器字段截取内容做为简介
            if($v['formtype']=="editor"){
                //如果开启了远程保存图片的话
                if($data[$v['field']."_saveFile"]){
                    $SaveRemoteImg=new \app\admin\model\SaveRemoteImgModel();
                    $data[$v['field']]=$SaveRemoteImg->doIt(htmlspecialchars_decode($data[$v['field']]));
                }
                //如果开启了提取第一张图做为缩略图并且缩略图为空的话
                if($data[$v['field']."_getFirstImg"]&&!$data["thumb"]){
                    $return["index"]["thumb"]=$this->getFirstImg($data[$v['field']]);
                }
                //提取简介
                if(!$data['description']){
                    $data['description']= mb_substr(strip_tags($data[$v['field']]),0,config("setting.description_len"),'utf-8');
                }
            }  
            //判断是否为 int smallint tinyint bigint
            if(in_array($v['fieldtype'],array("tinyint","smallint","int","bigint"))){
               $data[$v['field']]=abs($data[$v['field']]);//禁止出现负数 
            }    
            //保息信息处理函数
            if($v['savefun']&&strstr($v['savefun_trigger'],"|".$type."|")){
                $savefunArr=explode("###",$v['savefun']);
                $funVal=array();
                if($savefunArr[1]){
                    $funParmas=explode(",",$savefunArr[1]);
                    $funVal=array_merge(array($data[$v['field']]),$funParmas);
                }else{
                    $funVal=array($data[$v['field']]);
                }    
                $data[$v['field']]=call_user_func_array($savefunArr[0],$funVal);
            }            
           //检测是不是副表字段
             if($v['issystem']){
                $return["index"][$v['field']]=$data[$v['field']];
            }else{
                $return["data"][$v['field']]=$data[$v['field']];
            }
        }
        //系统字段
        $default_field=["id","cache_id","catid","modelid","pagetitle","keywords","description","titleurl","link","pubid","sort","userid","username","addtime","editortime","is_good","is_top","favs","viewtemp"];
        $data["modelid"]=$this->ModelInfo["modelid"];
        $data["userid"]=$this->user_id;
        $data["username"]=$this->username;
        $data["addtime"]=time();
        $data["editortime"]=time();
        foreach($default_field as $field){
            if(isset($data[$field])){
                $return["index"][$field]=$data[$field];
            }
        }   
        return $return;
    }    
    //栏目分类
    public function getCat(){
        $catstr=$this->forCat(0);
        header("Content-type:text/html;charset=utf-8");
        echo '<select name="catid">';
        echo $catstr;
        echo '</select>';   
        exit;
    }
    protected function forCat($pid=0,$str=""){
        $where["pid"]=$pid?$pid:0;
        $where["status"]=1;
        $cat=Db::name("cat")->where($where)->order("sort asc,catid asc")->select();  
        if(count($cat)>0){
            foreach($cat as $v){               
                $nbsp_str="";
                for($i=1;$i<$v[level];$i++){
                    $nbsp_str.="&nbsp;&nbsp;";
                }
                if($this->catid&&$this->catid==$v['catid']){
                    $this_selected="selected";
                }else{
                    $this_selected="";
                }
                $str.="<option value='{$v['catid']}' ".$this_selected.">{$nbsp_str}|-{$v['name']}</option>";
                $str=$this->forCat($v['catid'],$str);                
            }            
            return $str;
        }else{
            return $str;
        }
    }  
    //提取内容第一张图做为缩略图
    private function getFirstImg($str){
        preg_match("/\<[img|IMG].*?src=\"(.+?)\".*?>/",$str,$result);
        return $result[1];
    }  
    protected function success(){
        echo "success";exit;
    }    
    protected function error($err){
        echo "error\r\n".$err;exit;
    }
}